
package com.zdkj.subway.st.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.constant.enums.StockEnum;
import com.zdkj.subway.st.entity.*;
import com.zdkj.subway.st.mapper.SwStTicketBorrowReturnMapper;
import com.zdkj.subway.st.service.SwStTicketBorrowReturnService;
import com.zdkj.subway.st.util.GenSerialNo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;

@Slf4j
@Service
@AllArgsConstructor
public class SwStTicketBorrowReturnServiceImpl extends ServiceImpl<SwStTicketBorrowReturnMapper, SwStTicketBorrowReturn> implements SwStTicketBorrowReturnService {

    @Autowired
    private SwStOutputDetailServiceImpl sdcd;

    @Autowired
    private SwStInputDetailServiceImpl rkcd;

    @Autowired
    private GenSerialNo genSerialNo;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SwStTicketBorrowReturn swStTicketBorrowReturn) {
        return  this.saveborrowandsotock(swStTicketBorrowReturn);
    }

    /**
     * 借出执行出库操作
     * @param swStTicketBorrowReturn
     * @return
     */
    private boolean saveborrowandsotock(SwStTicketBorrowReturn swStTicketBorrowReturn){
        boolean issuccuess=true;
        String stocktype= StockEnum.StockType.OUTSTOCK.getValue();
        //借用出库
        String outstockvalue=StockEnum.OutputStock.JYCK.getValue();
        try {
            //根据票种生成单号前缀
            String prefix = genSerialNo.getPreFixByTicketType(swStTicketBorrowReturn.getTicketType());
            String serialno=genSerialNo.genSerioNo(stocktype);
            PigxUser user = SecurityUtils.getUser();
            //执行出库操作
            SwStOutputDetail swStOutputDetail=SwStOutputDetail.builder().creatorId(user.getId()).
                    creatorName(user.getUsername()).ticketType(swStTicketBorrowReturn.getTicketType()).
                    outGoingType(outstockvalue).createTime(LocalDateTime.now()).outstockno(prefix+serialno)
                    .stockArea(swStTicketBorrowReturn.getStockArea())
                    .ticketNumber(swStTicketBorrowReturn.getBorrowNumber()).build();
            sdcd.save(swStOutputDetail);
            if(!issuccuess)
            {
                issuccuess=false;
                throw new RuntimeException("库存更新异常！");
            }
            //其次更新入库基础表
            swStTicketBorrowReturn.setCreatorName(user.getUsername());
            swStTicketBorrowReturn.setCreatorId(user.getId());
            //设置关联库存id
            swStTicketBorrowReturn.setOutputStockid(swStOutputDetail.getId());
            swStTicketBorrowReturn.setOutputStockno(prefix+serialno);
        }catch (Exception e){
            log.error("",e);
            throw new RuntimeException(e);
        }
        return issuccuess&&super.save(swStTicketBorrowReturn);
    }

    /**
     * 通过库存更新领用信息
     * @param swStOutputDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean borrowsave(SwStOutputDetail swStOutputDetail) {
        try {
            SwStTicketBorrowReturn swStTicketBorrowReturn=new SwStTicketBorrowReturn();
            swStTicketBorrowReturn.setOutputStockno(swStOutputDetail.getOutstockno());
            swStTicketBorrowReturn.setOutputStockTime(swStOutputDetail.getOutGoingTime());
            swStTicketBorrowReturn.setTicketType(swStOutputDetail.getTicketType());
            swStTicketBorrowReturn.setActiveTime(swStOutputDetail.getActiveTime());
            swStTicketBorrowReturn.setTicketNo(swStOutputDetail.getTicketNo());
            swStTicketBorrowReturn.setBorrowNumber(swStOutputDetail.getTicketNumber());
            swStTicketBorrowReturn.setStockArea(swStOutputDetail.getStockArea());
            swStTicketBorrowReturn.setBorrowTime(swStOutputDetail.getOutGoingTime());
            swStTicketBorrowReturn.setIsReceive("否");
            swStTicketBorrowReturn.setIsReturn("否");
            swStTicketBorrowReturn.setOutputStockid(swStOutputDetail.getId());
            swStTicketBorrowReturn.setTicketName(swStOutputDetail.getTicketName());
            swStTicketBorrowReturn.setTicketPrice(swStOutputDetail.getTicketPrice());
            swStTicketBorrowReturn.setTicketTimes(swStOutputDetail.getTicketTimes());
            swStTicketBorrowReturn.setTicketType(swStOutputDetail.getTicketType());
            swStTicketBorrowReturn.setOutputStockid(swStOutputDetail.getId());
			swStTicketBorrowReturn.setOutputPersonCode(swStOutputDetail.getKeepercode());//出库人  setOutputPersonCode
			swStTicketBorrowReturn.setOutputPersonName(swStOutputDetail.getKeepername());//出库人工号
            swStTicketBorrowReturn.setFile(swStOutputDetail.getFilePath());
            swStTicketBorrowReturn.setPicture(swStOutputDetail.getPicturePath());
            return super.save(swStTicketBorrowReturn);
        }catch (Exception e){
            log.error("",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 归还执行入库操作
     * @param swStTicketBorrowReturn
     * @return
     */
    private SwStInputDetail savereturnandsotock(SwStTicketBorrowReturn swStTicketBorrowReturn) throws Exception{
        String stocktype= StockEnum.StockType.INSTOCK.getValue();
        //借用出库
        String instockvalue=StockEnum.InputStock.GHRK.getValue();
        //根据票种生成单号前缀
        String prefix = genSerialNo.getPreFixByTicketType(swStTicketBorrowReturn.getTicketType());
        String serialno = genSerialNo.genSerioNo(stocktype);
        PigxUser user = SecurityUtils.getUser();
        SwStInputDetail swStInputDetail=SwStInputDetail.builder().creatorId(user.getId())
                .creatorName(user.getUsername()).ticketType(swStTicketBorrowReturn.getTicketType())
                .createTime(LocalDateTime.now()).instockno(prefix+serialno).inGoingType(instockvalue)
                .stockArea(swStTicketBorrowReturn.getStockArea())
                .ticketNumber(swStTicketBorrowReturn.getReturnNumber()).build();
        rkcd.save(swStInputDetail);
        return swStInputDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(SwStTicketBorrowReturn swStTicketBorrowReturn){
        //try {
        //    SwStOutputDetail swStOutputDetail=sdcd.getById(swStTicketBorrowReturn.getOutputStockid());
        //    swStOutputDetail.setTicketNumber(swStTicketBorrowReturn.getBorrowNumber());
        //    //首先更新库存
        //    if(swStOutputDetail.getId() != null){
        //        sdcd.getBaseMapper().updateById(swStOutputDetail);
        //    }else {
        //        sdcd.getBaseMapper().insert(swStOutputDetail);
        //    }
        //
        //    //获取更新前数据
        //    SwStTicketBorrowReturn oldsstbr=super.getById(swStTicketBorrowReturn.getId());
        //    //新增的id
        //    if(oldsstbr.getReturnNumber()==0 && swStTicketBorrowReturn.getReturnNumber() != null && swStTicketBorrowReturn.getReturnNumber()>0)
        //    {
        //        SwStInputDetail swStInputDetail=this.savereturnandsotock(swStTicketBorrowReturn);
        //        swStTicketBorrowReturn.setInputStockid(swStInputDetail.getId());
        //        swStTicketBorrowReturn.setInputStockno(swStInputDetail.getInstockno());
        //    }
        //    //如果历史数据已归还，则更新库存账
        //    if(oldsstbr.getReturnNumber()>0) {
        //        //更新归还数量
        //        SwStInputDetail swStInputDetail=rkcd.getById(swStTicketBorrowReturn.getInputStockid());
        //        swStInputDetail.setTicketNumber(swStTicketBorrowReturn.getReturnNumber());
        //        //首先更新库存
        //        if(!rkcd.saveOrUpdate(swStInputDetail))
        //        {
        //            throw new RuntimeException("更新入库存异常!");
        //        }
        //    }
        //}catch (Exception e)
        //{
        //    log.error("",e);
        //    throw new RuntimeException(e);
        //}
        //更新入库数据
        return super.updateById(swStTicketBorrowReturn);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        //级联删除库存
        SwStTicketBorrowReturn swStTicketBorrowReturn= super.getById(id);
        long outputstockdayid=swStTicketBorrowReturn.getOutputStockid()!=null?swStTicketBorrowReturn.getOutputStockid():0;
        long inputstockdayid=swStTicketBorrowReturn.getInputStockid()!=null?swStTicketBorrowReturn.getInputStockid():0;
        if(outputstockdayid!=0&&!sdcd.removeById(outputstockdayid))
        {
            throw new RuntimeException("更新库存异常!");
        }
        if(inputstockdayid!=0&&!rkcd.removeById(inputstockdayid)){
            throw new RuntimeException("更新库存异常!");
        }
        return super.removeById(id);
    }
}
